﻿using System;
using VMWorkshop.Web.Models;
using VMWorkshop.Web.Models.ViewModels;
using VMWorkshop.Domain;

namespace VMWorkshop.Web
{
    public partial class WebForms : System.Web.UI.Page
    {
        protected WebFormsViewModel _vm;

        protected void Page_Init(object sender, EventArgs e)
        {
            this._vm = new WebFormsViewModel(new ProductRepository());
        }

        protected void grdProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
            string productId = this.grdProducts.DataKeys[this.grdProducts.SelectedIndex][0].ToString();
            this._vm.GetSelectedProduct(productId);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.Page.Validate();

            if (this.Page.IsValid)
            {
                ProductEditView view = new ProductEditView();
                view.Description = this.description.Text;
                view.Price = this.price.Text;
                view.ProductId = this.productId.Value;
                view.QuantityOnHand = this.quantityOnHand.Text;
                view.ReleaseDate = this.releaseDate.Text;
                view.Title = this.title.Text;
                this._vm.PersistChanges(view);
            }
        }

        // The reason for using the PreRender event handler is to give the
        // control event handlers (see above) a chance to fire in the Page
        // event life cycle before the page finalizes binding data to controls
        // and setting visibility to items.
        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                this.grdProducts.DataSource = this._vm.Products;
                this.grdProducts.DataBind();
            }

            this.plcEditor.Visible = this._vm.HasSelectedProduct;
            this.plcSaveComplete.Visible = this._vm.IsPersistenceSuccessful;

            this.title.Text = this._vm.SelectedProduct.Title;
            this.description.Text = this._vm.SelectedProduct.Description;
            this.quantityOnHand.Text = this._vm.SelectedProduct.QuantityOnHand;
            this.releaseDate.Text = this._vm.SelectedProduct.ReleaseDate;
            this.price.Text = this._vm.SelectedProduct.Price;
            this.productId.Value = this._vm.SelectedProduct.ProductId;
        }
    }
}
